package com.bittech.everything.cmd;

import com.bittech.everything.config.EverythingConfig;
import com.bittech.everything.core.EverythingManager;
import com.bittech.everything.core.dao.DataSourceFactory;
import com.bittech.everything.core.model.Condition;
import com.bittech.everything.core.model.Thing;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * Everything主程序
 * 基于字符界面进行交互式访问
 * <p>
 * Author: secondriver
 * Created: 2018/9/26
 */
public class EverythingCmdApp {
    
    public static void main(String[] args) {
        //解析参数
        parseParam(args);
        
        //配置
        final EverythingConfig config = EverythingConfig.getInstance();
        
        //管理器
        EverythingManager everythingManager = EverythingManager.getInstance();
        
        //构建索引
        if (config.isRebuildIndex()) {
            index(everythingManager);
        }
        
        //启动清理
        everythingManager.startBackgroundClear();
        
        //启动监控
        everythingManager.startBackgroundMonitor();
        
        //交互式
        interactive(config, everythingManager);
        
    }
    
    private static void interactive(EverythingConfig config, EverythingManager manager) {
        Scanner scanner = new Scanner(System.in);
        doWelcome();
        while (true) {
            System.out.print(">>");
            String line = scanner.nextLine().trim();
            if (line.startsWith("search")) {
                String[] params = line.split(" ");
                if (params.length >= 2) {
                    Condition condition = new Condition();
                    condition.setName(params[1]);
                    if (params.length == 3) {
                        condition.setFileType(params[2]);
                    }
                    condition.setOrderByAsc(config.isDepthAsc());
                    condition.setLimit(config.getMaxReturnFile());
                    doSearch(condition, manager);
                } else {
                    doHelp();
                }
            } else {
                switch (line) {
                    case "quit":
                        doQuit();
                        return;
                    case "help":
                        doHelp();
                        break;
                    case "index":
                        index(manager);
                        break;
                    default:
                        doHelp();
                        break;
                }
            }
        }
    }
    
    /**
     * 参数解析
     *
     * @param args 程序入口参数
     */
    private static void parseParam(String[] args) {
        EverythingConfig config = EverythingConfig.getInstance();
        for (String paramLine : args) {
            if (paramLine.startsWith("--indexPaths=")) {
                int index = paramLine.indexOf("=");
                String indexPathsStr = paramLine.substring(index + 1);
                String[] indexPaths = indexPathsStr.split(",");
                //配置中索引路径集合不为空，先清空默认值
                if (!config.getIndexPaths().isEmpty()) {
                    config.getIndexPaths().clear();
                }
                config.getIndexPaths().addAll(Arrays.asList(indexPaths));
            }
            if (paramLine.startsWith("--excludePaths=")) {
                int index = paramLine.indexOf("=");
                String excludePathsStr = paramLine.substring(index + 1);
                String[] excludePaths = excludePathsStr.split(",");
                //配置中排除的索引路径集合不为空，先清空默认值
                if (!config.getExcludePaths().isEmpty()) {
                    config.getExcludePaths().clear();
                }
                config.getExcludePaths().addAll(Arrays.asList(excludePaths));
            }
            
            if (paramLine.startsWith("--maxRecentlyFile=")) {
                int index = paramLine.indexOf("=");
                int maxRecentlyFile = 30;
                try {
                    maxRecentlyFile = Integer.parseInt(paramLine.substring(index + 1));
                } catch (NumberFormatException e) {
                    System.out.println("Warning: param maxRecentlyFile can't convert number");
                }
                config.setMaxRecentlyFile(maxRecentlyFile);
            }
            
            if (paramLine.startsWith("--maxReturnFile=")) {
                int index = paramLine.indexOf("=");
                int maxReturnFile = 30;
                try {
                    maxReturnFile = Integer.parseInt(paramLine.substring(index + 1));
                } catch (NumberFormatException e) {
                    System.out.println("Warning: param maxReturnFile can't convert number");
                }
                config.setMaxReturnFile(maxReturnFile);
            }
            if (paramLine.startsWith("--depthAsc=")) {
                int index = paramLine.indexOf("=");
                boolean depthAsc = true;
                try {
                    depthAsc = Boolean.parseBoolean(paramLine.substring(index + 1));
                } catch (NumberFormatException e) {
                    System.out.println("Warning: param depthAsc can't convert bool");
                }
                config.setDepthAsc(depthAsc);
            }
            
            if (paramLine.startsWith("--rebuildIndex=")) {
                int index = paramLine.indexOf("=");
                boolean rebuildIndex = true;
                try {
                    rebuildIndex = Boolean.parseBoolean(paramLine.substring(index + 1));
                } catch (NumberFormatException e) {
                    System.out.println("Warning: param rebuildIndex can't convert bool");
                }
                config.setRebuildIndex(rebuildIndex);
            }
        }
    }
    
    
    /**
     * 索引
     *
     * @param everythingManager 管理器
     */
    private static void index(EverythingManager everythingManager) {
        DataSourceFactory.databaseInit();
        System.out.println("Rebuild File System Index ...");
        Thread buildIndexThread = new Thread(everythingManager::buildIndex);
        buildIndexThread.setDaemon(false);
        buildIndexThread.start();
    }
    
    /**
     * 欢迎
     */
    private static void doWelcome() {
        System.out.println("欢迎使用，Everything");
    }
    
    /**
     * 退出 quit
     */
    private static void doQuit() {
        System.out.println("欢迎使用，再见");
        System.exit(0);
    }
    
    /**
     * 帮助 help
     */
    private static void doHelp() {
        System.out.println("命令列表：");
        System.out.println("退出：quit");
        System.out.println("帮助：help");
        System.out.println("索引：index");
        System.out.println("搜索：search <name> [<file-Type> img | doc | bin | archive | other]");
    }
    
    /**
     * 检索 search
     *
     * @param condition 查询信息
     * @param manager   管理器
     */
    private static void doSearch(Condition condition, EverythingManager manager) {
        List<Thing> thingList = manager.search(condition);
        thingList.forEach((t) -> System.out.println(t.getPath()));
    }
}